package edu.gyc.hiwhore.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import edu.gyc.hiwhore.model.Girl;
import edu.gyc.hiwhore.dao.GirlDao;
import edu.gyc.hiwhore.service.GirlService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ls
 * @since 2021-08-03
 */
@Service
@Slf4j
@CacheConfig(cacheNames = "whore")
public class GirlServiceImpl extends ServiceImpl<GirlDao, Girl> implements GirlService {
    //其中#p0是指的第一个参数，#p1是第二个参数，以此类推。
    @Override
    @Cacheable(key = "'girl-id-'+#p0")
//    @Cacheable(value = "girl",key = "#id",condition = "#id>1")
    public Girl getById(Serializable id) {
       log.info("From db query girl :"+id);
        return super.getById(id);
    }

    @CacheEvict(key = "'girl-id-'+#girl.id",allEntries = true)
//    @CachePut(value = "girl",key = "#girl.id")
    public Girl update(Girl girl) {
        log.info("update girl id:"+girl.getId());
//         this.updateById(girl);
        //只更新非空字段
        LambdaUpdateWrapper<Girl> updateWrapper = Wrappers.<Girl>lambdaUpdate()
                .eq(Girl::getId,girl.getId())
                .set(StringUtils.isNotBlank(girl.getName()), Girl::getName, girl.getName())
                .set(StringUtils.isNotBlank(girl.getGender()),Girl::getGender,girl.getGender())
//                .set(ObjectUtils.isNotNull(girl.getBirthday()),Girl::getBirthday,girl.getBirthday())
                .set(StringUtils.isNotBlank(girl.getMajor()),Girl::getMajor,girl.getMajor())
                .set(ObjectUtils.isNotNull(girl.getPrice()),Girl::getPrice,girl.getPrice());


        this.update(updateWrapper);
//        Girl t = getById(girl.getId());
//        for(Girl )
        return getById(girl.getId());
    }

    @Override
    @CacheEvict(key = "'girl-id-'+#p0")
    public boolean del(Integer id) {

        return this.removeById(id);
    }

    @Override
    @CachePut(key = "'girl-id-'+#girl.id")
    public boolean addGirl(Girl girl) {
        return this.save(girl);
    }

    @Override
//    @Cacheable(cacheNames = "girlList")
    public List<Girl> allGirls() {
        return this.list();
    }


}
